package io.github.lee.core.views

import android.content.Context
import android.util.AttributeSet
import android.widget.RelativeLayout
import androidx.databinding.BindingAdapter
import io.github.lee.core.ui.R


@BindingAdapter(value = ["rl_ratio"], requireAll = false)
fun RatioRelativeLayout.ratio(ratio: Float?) {
    this.ratio = ratio ?: 0F
}

@BindingAdapter(value = ["rl_benchmark"], requireAll = false)
fun RatioRelativeLayout.rl_benchmark(benchmark: Int?) {
    this.benchmark = benchmark ?: RatioRelativeLayout.BENCHMARK_WIDTH
}

/**
 * 等比例缩放的 RelativeLayout
 *
 */
class RatioRelativeLayout : RelativeLayout {
    companion object {
        const val BENCHMARK_WIDTH = 0
        const val BENCHMARK_HEIGHT = 1
    }

    var ratio = 0F
    var benchmark = 0

    //===Desc:===============================================================================

    constructor(context: Context?) : this(context, null)
    constructor(context: Context?, attrs: AttributeSet?) : this(context, attrs, 0)
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : this(
        context,
        attrs,
        defStyleAttr, 0
    )

    constructor(
        context: Context?,
        attrs: AttributeSet?,
        defStyleAttr: Int,
        defStyleRes: Int
    ) : super(context, attrs, defStyleAttr, defStyleRes) {
        init(context, attrs)
    }

    //===Desc:===============================================================================

    private fun init(context: Context?, attrs: AttributeSet?) {
        val typedArray =
            context?.obtainStyledAttributes(attrs, R.styleable.RatioRelativeLayout)
        ratio = typedArray?.getFloat(R.styleable.RatioRelativeLayout_rl_ratio, 0.0F) ?: 0F
        benchmark = typedArray?.getInt(R.styleable.RatioRelativeLayout_rl_benchmark, 0) ?: 0
        typedArray?.recycle()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        if (benchmark == BENCHMARK_WIDTH) {
            var hms = heightMeasureSpec
            val width = MeasureSpec.getSize(widthMeasureSpec)
            val widthMode = MeasureSpec.getMode(widthMeasureSpec)
            if (widthMode == MeasureSpec.EXACTLY && ratio != 0.0f) {
                val height = width / ratio
                hms = MeasureSpec.makeMeasureSpec(height.toInt(), MeasureSpec.EXACTLY)
            }
            super.onMeasure(widthMeasureSpec, hms)
        } else {
            var wms = widthMeasureSpec
            val height = MeasureSpec.getSize(heightMeasureSpec)
            val heightMode = MeasureSpec.getMode(widthMeasureSpec)
            if (heightMode == MeasureSpec.EXACTLY && ratio != 0.0f) {
                val width = height / ratio
                wms = MeasureSpec.makeMeasureSpec(width.toInt(), MeasureSpec.EXACTLY)
            }
            super.onMeasure(wms, heightMeasureSpec)
        }

    }
}